package com.yingxue.lesson.service.impl;

import com.yingxue.lesson.entity.SysRolePermission;
import com.yingxue.lesson.exception.BusinessException;
import com.yingxue.lesson.exception.code.BaseResponseCode;
import com.yingxue.lesson.mapper.SysRolePermissionMapper;
import com.yingxue.lesson.service.RolePermissionService;
import com.yingxue.lesson.vo.req.RolePermissionOperationReqVO;
import com.yingxue.lesson.vo.req.userVo.UserOwnRoleReqVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class RolePermissionServiceImpl implements RolePermissionService {

    @Autowired
    private SysRolePermissionMapper rolePermissionMapper;

    /**
     * 添加角色权限中间表
     */
    @Override
    public void addRolePermission(RolePermissionOperationReqVO vo) {
        rolePermissionMapper.removeByRoleId(vo.getRoleId());
        if (vo.getPermissionIds() == null || vo.getPermissionIds().isEmpty()){
            return;
        }
        ArrayList<SysRolePermission> list = new ArrayList<>();
        for (String permissionId: vo.getPermissionIds()) {
            SysRolePermission rolePermission = new SysRolePermission();
            rolePermission.setId(UUID.randomUUID().toString());
            rolePermission.setCreateTime(new Date());
            rolePermission.setRoleId(vo.getRoleId());
            rolePermission.setPermissionId(permissionId);
            list.add(rolePermission);
        }
        int i = rolePermissionMapper.batchAddRolePermission(list);
        if (i==0){
            throw new BusinessException(BaseResponseCode.OPERATION_ERROR);
        }
    }


    /**
     * 根据权限id查询角色id 集合
     */
    @Override
    public List<String> getRoleIdsByPermissionId(String permissionId) {
        return rolePermissionMapper.getRoleIdsByPermissionId(permissionId);
    }

    /**
     * 根据permissionId 删除角色和菜单权限关联表相关数据
     */
    @Override
    public void removeByPermission(String permission) {
        rolePermissionMapper.removeByPermission(permission);
    }

    /**
     * 根据角色id获取该角色关联的菜单权限id集合
     */
    @Override
    public List<String> getPermissionIdsByRoleId(String roleId) {
        return rolePermissionMapper.getPermissionIdsByRoleId(roleId);
    }

    /**
     * 根据角色id删除角色和菜单权限关联表相关数据
     */
    @Override
    public int removeByRoleId(String roleId) {
        return rolePermissionMapper.removeByRoleId(roleId);
    }

    /**
     * 根据 roleIds 查询 permissionIds
     */
    @Override
    public List<String> getPermissionIdsByRoleIds(List<String> roleIds) {
        return rolePermissionMapper.getPermissionIdsByRoleIds(roleIds);
    }
}
